var Info = {
    id:"" ,
    courseInfo:""
};

//返回到课程发布页面
$("#btn-back").on("click",function(){
    window.location.href = Feng.ctxPath+"/course/list/page";
});
function backCourseListPage() {
    window.location.href = Feng.ctxPath + "/course/list/page";
}

//查询课程类型
Info.courseType = function () {
    var ajax = new $ax(Feng.ctxPath+"/classType/getClassTypeList", function(data){
        Feng.log("课程类型查询成功");
        var obj = data.obj || [];
        if (obj.length>0){
            var selectItem = "";
            for(var i=0,len=obj.length; i<len; i++){
                selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].classTypeName);
            }
            $("#classTypeId").append(selectItem);
        }
    },function(data){
        Feng.error("课程类型查询失败!");
    });
    ajax.start();
};

//获取省
Info.province = function () {
    var ajax = new $ax(Feng.ctxPath+"/province/getProvinceList", function(data){
        Feng.log("省查询成功");
        var obj = data.obj || [];
        if (obj.length>0){
            var selectItem = "";
            for(var i=0,len=obj.length; i<len; i++){
                selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].name);
            }
            $("#provinceId").append(selectItem);
        }
    },function(data){
        Feng.error("省查询失败!");
    });
    ajax.start();
};

//选择省获取市
$("#provinceId").on("change",function () {
    var selectItem = "<option value=''>--请选择市--</option>";
    if($(this).val() !== ""){
        var ajax = new $ax(Feng.ctxPath+"/province/selectLocByProvinceId", function(data){
            Feng.log("市查询成功");
            var obj = data.obj || [];
            if (obj.length>0){

                for(var i=0,len=obj.length; i<len; i++){
                    selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].city);
                }
                $("#location").html(selectItem);
            }
        },function(data){
            Feng.error("市查询失败!");
        });
        ajax.data={provinceId:$(this).val()};
        ajax.start();
    }
    else{
        $("#location").html(selectItem);
    }
});

//选择市获取校区
$("#location").on("change",function () {
    var selectItem = "<option value=''>--请选择校区--</option>";
    if($(this).val() !== ""){
        var options = {
            cityId:$(this).val(),
            current:1,
            size:999
        };
        var ajax = new $ax(Feng.ctxPath+"/school/allParam", function(data){
            Feng.log("市查询成功");
            var obj = data.records || [];
            if (obj.length>0){

                for(var i=0,len=obj.length; i<len; i++){
                    selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].schoolName);
                }

            }
            $("#campus").html(selectItem);
        },function(data){
            Feng.error("市查询失败!");
            $("#campus").html(selectItem);
        });
        ajax.set(options);
        ajax.start();
    }
    else{
        $("#campus").html(selectItem);
    }
});

//查询讲师列表
Info.teacher = function () {
    var ajax = new $ax(Feng.ctxPath+"/teacher/allListParam", function(data){
        Feng.log("省查询成功");
        var obj = data.obj || [];
        if (obj.length>0){
            var selectItem = "";
            for(var i=0,len=obj.length; i<len; i++){
                selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].truename);
            }
            $("#teacherMainId").append(selectItem);
        }
    },function(data){
        Feng.error("省查询失败!");
    });
    ajax.setData({"roleId":2});
    ajax.start();
};

//查询讲师列表
Info.teacherHelp = function () {
    var ajax = new $ax(Feng.ctxPath + "/teacher/selectTeacherHelp", function (data) {
        Feng.log("省查询成功");
        var obj = data.obj || [];
        if (obj.length>0){
            var selectItem = "";
            for(var i=0,len=obj.length; i<len; i++){
                selectItem+="<option value='{0}'>{1}</option>".format(obj[i].id,obj[i].truename);
            }
            $("#teacherHelpId").append(selectItem);
        }
    },function(data){
        Feng.error("省查询失败!");
    });
    ajax.setData();
    ajax.start();
};

//查询课程详情
Info.courseDetail = function () {
    var ajax = new $ax(Feng.ctxPath+"/course/getById", function(data){
        Feng.log("查询详情成功");
        if (data.success){
            var cicyList = data.obj.city || [],
                course = data.obj.course,
                classTypeList = data.obj.classType || [],
                provinceList = data.obj.province || [],
                schoolList = data.obj.school || [];

            //获取市
            var cityHtml = "<option value=''>--请选择市--</option>";
            if (cicyList.length>0){
                for(var i=0,len=cicyList.length; i<len; i++){
                    cityHtml+="<option value='{0}'>{1}</option>".format(cicyList[i].id,cicyList[i].city);
                }
                $("#location").html(cityHtml);
            }

            //获取显示学校
            var schoolHtml = "<option value=''>--请选择校区--</option>";
            if (schoolList.length>0){
                for(var i=0,len=schoolList.length; i<len; i++){
                    schoolHtml+="<option value='{0}'>{1}</option>".format(schoolList[i].id,schoolList[i].schoolName);
                }
                $("#campus").html(schoolHtml);
            }
            //显示课程信息
            for (var i in course){
                //判断Id与name是否相同
                if($("#"+i).attr("name")==i){
                    $("#"+i).val(course[i]);
                }
            }
            //课程介绍
            console.log("couse:"+course.courseInfo);
            Info.courseInfo = course.courseInfo;

            //初始化开始和结束时间
            if(course.courseStartDate!=""){
                $("#courseStartDate").val(course.courseStartDate.split(' ')[0]);
            }

            //上课时间
            if(course.classStartTime!==null && course.classStartTime!==""){
                var startTime = course.classStartTime.split(':');
                $(".classStartTime").eq(0).val(startTime[0]);
                $(".classStartTime").eq(1).val(startTime[1].substring(0,2));
            }
            // 下课时间
            if(course.classEndTime!==null && course.classEndTime!==""){
                var endTime = course.classEndTime.split(':');
                $(".classEndTime").eq(0).val(endTime[0]);
                $(".classEndTime").eq(1).val(endTime[1].substring(0,2));
            }

            //图片
            var picName = ["picture1","picture2","picture3","picture4","picture5"],
                picHtml = "";
            for(var i=0,len=picName.length; i<len; i++){
                if(data.obj.course[picName[i]]!==null){
                    picHtml += "<div class='item col-md-2 thumbnail' style='background-image:url("+Feng.ctxPath+"/file/getImage/"+data.obj.course[picName[i]]+");'>" +
                        "<a class=\"btn-close glyphicon glyphicon-remove\" data-name='"+data.obj.course[picName[i]]+"'></a>" +
                        "</div>";
                }

            }

            //视频
            if(data.obj.course.video!=="" && data.obj.course.video!==undefined)
                $("#btn-download").attr("href",Feng.ctxPath+"/file/download/"+data.obj.course.video).show();

            $("#img_list").html(picHtml);
            Info.displayUploadBtn();

        }
    },function(data){
        Feng.error("查询详情失败!");
    });
    ajax.set("id",Info.id);
    ajax.start();
};


//保存课程信息
$("#btn-save").on("click",function () {
    var options = getFormJson("#frmMain");
    options.id = Info.id;
    options.courseStatus = options.courseStatus || "2";
    //上课时间
    options.classStartTime = $(".classStartTime").eq(0).val()+":"+$(".classStartTime").eq(1).val();
    options.classEndTime = $(".classEndTime").eq(0).val()+":"+$(".classEndTime").eq(1).val();
    //课程介绍
    options.courseInfo =  Base64.encode( UE.getEditor('content').getContent());

    if(options.classStartTime == ":" || options.classEndTime == ":"){
        Feng.error("上课时间不能为空");
        return;
    }

    var ajax = "";
    //添加图片
    var fileObj = {};
    var countIndex = $(".nav-tabs .active").index();
    if(countIndex===0)
        fileObj = Info.getUploadImgName();
    else{}

    if(JSON.stringify(fileObj)!=="{}"){
        options = $.extend(options,fileObj);
    }

    if(Info.id){
        ajax = new $ax(Feng.ctxPath+"/course/update", function(data){
            if (data.success) {
                Feng.success("修改成功!");
                Info.courseDetail();
                // window.location.href = Feng.ctxPath + "/course/list/page";

            } else if (data.code === 2) {
                Feng.error(data.msg);
            } else {
                Feng.error("修改失败!");
            }
        },function(data){
            Feng.error("修改失败!");
        });
    }
    else {
        ajax = new $ax(Feng.ctxPath+"/course/save", function(data){
            if (data.success) {
                Feng.success("新增成功");
                Info.courseDetail();
                // window.location.href = Feng.ctxPath + "/course/list/page";
            } else if (data.code === 2) {
                Feng.error(data.msg);
            } else {
                Feng.error("新增失败!");
            }
        },function(data){
            Feng.error("新增失败!");
        });
    }
    ajax.set(options);
    ajax.start();
});

//获取上传图片名称
Info.getUploadImgName = function () {
    var imgName = {};
    $("#img_list .btn-close").each(function (index) {
        var pictureName = $(this).attr("data-name");
        var index = parseInt(index)+1;
        imgName["picture"+index] = pictureName;
    });
    return imgName;
};

//图片上传
Info.initUploadImg = function () {
    $("#file").uploadify({
        height        : 30,
        swf           : Feng.ctxPath+'/js/assets/lib/uploadify/uploadify.swf?ver='+Math.random(),
        uploader      : Feng.ctxPath+'/file/upload?ver='+Math.random(),
        width         : 120,
        fileObjName   : 'file',
        fileTypeExts: '*.jpg;*.jpeg;*.png;', //文件后缀限制 默认：'*.
        fileSizeLimit: '3MB', //文件大小限制 0为无限制 默认KB
        queueSizeLimit :5,
        buttonText    : '图片上传', //按钮文字
        removeCompleted: true, //上传成功后的文件，是否在队列中自动删除
        overrideEvents: ['onSelectError','onSelect', 'onUploadSuccess', 'onUploadError'],//重写事件
        //选择关闭事件
        // onDialogClose:function () {},
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            Feng.error(msgText);
        },

        // 当选中文件时的回调函数
        'onSelect': function (file) {
            //显示上传状态
            $("#img_list").append("<div id='"+file.id+"_item' class='item col-md-2 thumbnail'>\n" +
                                        "<img src=\"../../superui/content/ui/img/loading-spinner-blue.gif\"/>\n" +
                                        "<span class=\"scale\">0%</span>\n" +
                                        "<a class=\"btn-close glyphicon glyphicon-remove\"></a>\n" +
                                    "</div>")
        },

        // 当文件上传中的回调方法
        'onUploadProgress': function (file, bytesUploaded, bytesTotal, totalBytesUploaded, totalBytesTotal) {
            // 设置进度条级显示的百分比
            var scale = Math.floor(bytesUploaded / bytesTotal) * 100;
            $("#"+file.id+"_item").children("span").html(scale + "%");
        },

        //检测FLASH失败调用
        'onFallback': function () {
            alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        ////文件上传成功后的回掉方法
        'onUploadSuccess':function (file, data, response) {
            console.log(data);
            var data = JSON.parse(data);
            if (data.code === 2){
                Feng.error(data.msg);
                return;
            }
            //清除加载进度比
            $("#"+file.id+"_item").children("span").remove();
            $("#"+file.id+"_item").children("img").remove();
            $("#"+file.id+"_item").children(".btn-close").attr("data-name",data.obj.fileName);
            // $("#"+file.id+"_item").append("<input type='hidden' name='' data-name='"+data.obj.fileName+"'></input>");

            //显示图片
            $("#"+file.id+"_item").attr("style","background-color: #ffffff;background-image:url({0}/file/getImage/{1})".format(Feng.ctxPath,data.obj.fileName));
            Info.displayUploadBtn();
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            Feng.error("上传出现异常，请重新上传" + errorString);
            $("#"+file.id+"_item").remove();
        }

    });
};

//视频上传控件初始化
Info.initUploadVideo = function () {

    $("#file_video").uploadify({
        height        : 30,
        swf           : Feng.ctxPath+'/js/assets/lib/uploadify/uploadify.swf?ver='+Math.random(),
        uploader      : Feng.ctxPath+'/file/upload-single?ver='+Math.random(),
        width         : 120,
        fileObjName   : 'file',
        // fileTypeExts: '*.jpg;*.jpeg;*.png;', //文件后缀限制 默认：'*.
        fileSizeLimit: '100MB', //文件大小限制 0为无限制 默认KB
        queueSizeLimit :1,
        multi: false,
        buttonText    : '视频上传', //按钮文字
        removeCompleted: true, //上传成功后的文件，是否在队列中自动删除
        overrideEvents: ['onSelectError', 'onUploadSuccess', 'onUploadError'],//重写事件
        //选择关闭事件
        //返回一个错误，选择文件的时候触发          
        'onSelectError': function (file, errorCode, errorMsg) {
            var msgText = "";
            switch (errorCode) {
                case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED:
                    //this.queueData.errorMsg = "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    msgText += "每次最多上传 " + this.settings.queueSizeLimit + "个文件";
                    break;
                case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT:
                    msgText += "文件大小超过限制" + this.settings.fileSizeLimit + "";
                    break;
                case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE:
                    msgText += "文件大小为0";
                    break;
                case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE:
                    msgText += "文件格式不正确，仅限 " + this.settings.fileTypeExts;
                    break;
                default:
                    msgText += "错误代码：" + errorCode + "\n" + errorMsg;
            }
            Feng.error(msgText);
        },

        //检测FLASH失败调用
        'onFallback': function () {
            alert("您未安装FLASH控件，无法上传图片！请安装FLASH控件后再试。");
        },

        ////文件上传成功后的回掉方法
        'onUploadSuccess':function (file, data, response) {
            var data = JSON.parse(data);
            if (data.code === 2){
                Feng.error(data.msg);
                return;
            }

            $("#video").val(data.obj.md5);
            //显示下载按钮
            $("#btn-download").attr("href",Feng.ctxPath+"/file/download/"+data.obj.md5).show();
            $("#btn-remove-video").show();
        },

        //文件上传出错时触发，参数由服务端程序返回。
        'onUploadError': function (file, errorCode, errorMsg, errorString) {
            Feng.error("上传出现异常，请重新上传" + errorString);
            // $("#"+file.id+"_item").remove();
        }

    });

};

//删除视频

//显示或隐藏上传按钮
Info.displayUploadBtn = function () {
    var length = $("#img_list .item").length;
    if(length==5) $("#file").hide();
    else $("#file").show();
};

//删除图片
$(document).on("click",".btn-close",function () {
    $(this).parent().remove();
    Info.displayUploadBtn();
});

//初始化上课时间
Info.initClassTime = function () {
    $(".timepicker").timepicker({
        defaultTime: 'value',
        showInputs: false,
        minuteStep:5,
        showMeridian:false//24小时
    });
    if(!Info.id)
    $(".timepicker").val("");
};

//初始化时间控件


$(function () {
    //初始化列表数据，课程类型、省、讲师、辅助老师
    Info.courseType();
    Info.province();
    Info.teacher();
    Info.teacherHelp();
    Info.initClassTime();
    Info.initUploadImg();
    Info.initUploadVideo();

    //获取url ID
    var args = getQueryStringArgs();
    Info.id = args["id"];
    //查询用户详情
    if(Info.id){
        Info.courseDetail();
        $("#cid").html(Info.id);
        $(".cid-row").removeClass("hide");
    }

    // layer.photos({
    //     photos: '#img_list'
    //     ,anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
    // });
});

editor.ready(function(){
    console.log(Info.courseInfo);
    editor.setContent(Info.courseInfo);
});


